import { Injectable, Injector, Inject } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { zip } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { MenuService, SettingsService, TitleService, ALAIN_I18N_TOKEN } from '@delon/theme';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { ACLService } from '@delon/acl';

import { NzIconService } from 'ng-zorro-antd/icon';
import { ICONS_AUTO } from '../../../style-icons-auto';
import { ICONS } from '../../../style-icons';
import { ApiService } from '@core/services/api';
import { UtilService } from '@core/services/util.service';
import { DicService } from '@core/services/dic.service';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { environment } from '@env/environment';

/**
 * Used for application startup
 * Generally used to get the basic data of the application, like: Menu Data, User Data, etc.
 */
@Injectable()
export class StartupService {
  dicMap: Map<string, {label, value}[]> = new Map<string, {label, value}[]>();
  ws: WebSocket;//定义websocket
  constructor(
    iconSrv: NzIconService,
    private menuService: MenuService,
    private settingService: SettingsService,
    private aclService: ACLService,
    private titleService: TitleService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private httpClient: HttpClient,
    private injector: Injector,
    private api: ApiService,
    public util: UtilService,
    private dic: DicService,
    private notification: NzNotificationService,
  ) {
    iconSrv.addIcon(...ICONS_AUTO, ...ICONS);
    
  }

  //socket连接
  connectWs() {
    let self=this;
    if (this.ws != null) { this.ws.close() };
    let url=""
    if(environment.SERVER_URL.indexOf('https') != -1){
      url=environment.SERVER_URL.replace("https","wss");
      url=url+":38380"
    }else{
      url=environment.SERVER_URL.replace("http","ws");
      url=url.replace("8000","38380");
    }
    console.log(url)
    //this.ws = new WebSocket("ws://192.168.2.140:38380/websocket");
    this.ws = new WebSocket(url+"/websocket");
    let that  = this;
    this.ws.onopen = function (event) {
            //socket 开启后执行，可以向后端传递信息
          //  that.ws.send('sonmething');
          console.log("连接成功");
    }
    this.ws.onmessage = function (event) {
            //socket 获取后端传递到前端的信息
            console.log("接收数据:");   
            console.log(event);
            self.notification.blank(
              '异常提醒',
              event.data,
            );
    }
    this.ws.onerror = function (event) {
            //socket error信息
            console.log('socket连接报错')
            console.log(event)
    }
    this.ws.onclose = function (event) {
            //socket 关闭后执行
            console.log('socket连接关闭')
           console.log(event)
    }
}

  private viaHttp(resolve: any, reject: any) {
    /*this.httpClient.get('http://localhost:4200/assets/tmp/app-data.json').subscribe(res => {
      console.log(res)
      const menu = res['menu'];
      this.menuService.add(menu)
    })*/
    zip(
      this.httpClient.get(this.api.user.info.url),
      // this.httpClient.post(this.api.dic.list.url, {})
    ).pipe(
      catchError(([ userInfo, /*dicData*/]) => {
          resolve(null);
          return [ userInfo, /*dicData*/];
      })
    ).subscribe(([ userInfo, /*dicData*/]) => {
      console.log(userInfo);
      this.util.setStorage('depts', userInfo.data.userCities);
      this.util.setStorage('userAccount',userInfo.data.userAccount);
      this.util.setStorage('roles',userInfo.data.roles.map((item)=>{
        return {"roleId":item.id}
      }))
      let obj={
        "userName" : userInfo.data.userName,
        "id" : userInfo.data.id,
        "userType":userInfo.data.userType,
        "userAccount":userInfo.data.userAccount
      }
      this.util.setStorage('userNow',obj);
      // Application data
      const res: any = userInfo.data;
       /** 菜单处理开始 */
      const menu = {
        text: 'Main',
        group: false,
        hideInBreadcrumb: true,
        children: []}
        let arr = [];
        const permit = [];
        const permission=[];
      res.roles.forEach(data => {
        const menuData = [];
         data.permissions.forEach( item => {
          if (item.menuType != 3) {
            const obj: any = {
              key: item.id,
              title: item.menuName,
              text: item.menuName,
              id: item.id,
              pId: item.menuParentId,
              link: item.menuUrl,
              permit: item.menuPermit,
              sort: item.menuSortno
            }
            if (item.menuIcon) {
              obj.icon = {type: 'icon', value: item.menuIcon}
            }
            menuData.push(obj);
          } else if (item.menuType == 3) {
            permit.push({name: item.menuName, permitCode: item.menuUrl});
            permission.push(item.menuUrl);
          }
        })
        this.util.setStorage('menu', menuData)
        this.util.setStorage('permit', permit);
        arr = [...menuData, ...arr]
      })
      menu.children = this.util.getTreeNodeOption(arr);
      // 菜单处理结束
        /* 字典处理开始 */
        /*dicData.data.map(item => {
          const obj = {label: item.dictCodeValue, value: Number(item.dictCode)};
          if (this.dic.dicMap.has(item.shineField)) {
            const dicArr = this.dic.dicMap.get(item.shineField);
            dicArr.push(obj);
            this.dic.dicMap.set(item.shineField, dicArr)
          } else {
            this.dic.dicMap.set(item.shineField, [obj])
          }
        })*/
     // console.log(this.dic.dicMap)
      /* 获取字典 */
      // Application information: including site name, description, year
        const app: any = {
          name: `兴天下智慧云平台`,
          description: `兴天下智慧云平台`
        };
        // const app: any = {
        //   name: `华为视频门禁系统`,
        //   description: `华为视频门禁系统`
        // };
      this.settingService.setApp(app);
      // User information: including name, avatar, email address
      const user = {name: res.userName, permit};
      this.settingService.setUser(user);
      // ACL: Set the permissions to full, https://ng-alain.com/acl/getting-started
      if(res.userAccount == "admin"){//超级管理员不受权限控制
        this.aclService.setFull(true);
      }else{
        this.aclService.setFull(false);
        this.aclService.setAbility(permission);//给当前用户设置按钮权限
      }
      //this.aclService.setFull(true);//给用户赋予所有的权限,检查按钮权限的方法全部返回true
      //console.log(this.aclService.canAbility("bc764f74e1a442749c2523a8c1946645"))//判断当前用户是否有对应的按钮权限
      // Menu data, https://ng-alain.com/theme/menu
      this.menuService.add([menu]);
      // Can be set page suffix title, https://ng-alain.com/theme/title
      this.titleService.suffix = app.name;
    },
    () => { },
    () => {
      resolve(null);
    });
  }

  private viaMock(resolve: any, reject: any) {
    // const tokenData = this.tokenService.get();
    // if (!tokenData.token) {
    //   this.injector.get(Router).navigateByUrl('/passport/login');
    //   resolve({});
    //   return;
    // }
    // mock
    const app: any = {
      name: `兴天下智慧云平台`,
      description: `兴天下智慧云平台`
    };
    const user: any = {
      name: 'Admin',
      avatar: './assets/tmp/img/avatar.jpg',
      email: 'cipchk@qq.com',
      token: '123456789'
    };
    // Application information: including site name, description, year
    this.settingService.setApp(app);
    // User information: including name, avatar, email address
    this.settingService.setUser(user);
    // ACL: Set the permissions to full, https://ng-alain.com/acl/getting-started
    this.aclService.setFull(true);
    // Menu data, https://ng-alain.com/theme/menu
    this.menuService.add([
      {
         text: 'Main',
        group: false,
        hideInBreadcrumb: true,
        children: [
          {
            text: '用户管理',
            link:'/user-manage',
            icon: { type: 'icon', value: 'user' },
            group: false,
            children:[  {
              text: '人员管理',
              link: '/user-manage/user-list'
            },{
              text: '重点人员管理',
              link:'/watch-person-manage',
              group: false,
              children:[
                {
                  text: '关注人员列表',
                  link: '/watch-person-manage/watch-person-list'
                },
                {
                  text: '关注人员出入记录',
                  link: '/watch-person-manage/watch-person-access'
                }
              ]
            },{
              text: '管理员设置',
              link: '/user-manage/manager-list'
            },{
              text: '门卡管理',
              link: '/user-manage/door-card'
            },{
              text: '开门授权管理',
              link: '/user-manage/autho-list'
            }]
          },
          {
            text:'出入记录管理',
            link:'/io-records-manage',
            icon:{type:'icon',value:'bulb'},
            group:false,
            children:[
              {
                text:'出入记录列表',
                link:'/io-records-manage/io-records-list'
              },
              {
                text:'抓拍记录',
                link:'/io-records-manage/camera-records-list'
              },
            ]
          },
          {
            text:'设备管理',
            link:'/device-manage',
            icon:{type:'icon',value:'mobile'},
            group:false,
            children:[
              {
                text:'设备列表',
                link:'/device-manage/device-list'
              },
              {
                text:'升级包管理',
                link:'/device-manage/upgrade-package-list'
              },
              {
                text:'设备升级管理',
                link:'/device-manage/device-list'
              },
              {
                text:'设备换机管理',
                link:'/device-manage/upgrade-package-list'
              }
            ]
          },
          {
            text:'告警管理',
            link:'/warning-manage',
            icon:{type:'icon',value:'warning'},
            group:false,
            children:[
              {
                text:'预警列表',
                link:'warning-manage/warning-list'
              },
              {
                text:'重点人员告警',
                link:'/warning-manage/warning-dic-list'
              },
              {
                text:'预警字典列表',
                link:'/warning-manage/warning-dic-list'
              }
            ]
          },
          {
            text: '房屋管理',
            link:'/house-manage',
            icon: { type: 'icon', value: 'appstore' },
            group: false,
            children:[{
              text: '房屋列表',
              link: '/house-manage'
            }]
          },
          {
            text: '系统管理',
            link: '/sys-setting',
            group: false,
            icon: {type: 'icon', value: 'setting'},
            children: [
              {
                text: '用户管理',
                link: '/sys-setting/user-manage'
              },
              {
                text: '角色管理',
                link: '/sys-setting/role-manage'
              },
              {
                text: '部门管理',
                link: '/sys-setting/per-group'
              },
              {
                text: '菜单管理',
                link: '/sys-setting/menu-manage'
              },
              {
                text: "区域管理",
                group: false,
                children: [
                  {
                    text: '社区管理',
                    link: '/sys-setting/area-manage/community-manage'
                  },
                  {
                    text: '警务区管理',
                    link:'/sys-setting/area-manage/police-manage'
                  },
                  {
                    text: '行政区划管理',
                    link: '/sys-setting/area-manage/area-list'
                  }
                ]
              }
            ]
          }
        ]
      }
    ]);
    // Can be set page suffix title, https://ng-alain.com/theme/title
    this.titleService.suffix = app.name;

    resolve({});
  }

  load(): Promise<any> {
    // only works with promises
    // https://github.com/angular/angular/issues/15088
    return new Promise((resolve, reject) => {
      // http
      this.viaHttp(resolve, reject);
      this.connectWs();
      // mock：请勿在生产环境中这么使用，viaMock 单纯只是为了模拟一些数据使脚手架一开始能正常运行
      // this.viaMock(resolve, reject);

    });
  }
}
